<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
            <div class="top-tab">
                <a-radio-group v-model:value="state.radioValue" button-style="solid" @change="radioChange">
                    <a-radio-button v-for="(item, index) in state.tabList" :value="item.id">{{
                        item.regionName
                    }}</a-radio-button>
                </a-radio-group>
            </div>
            <div class="content">
                <div class="opration">
                    <a-form-item label="时间范围">
                        <a-date-picker
                            style="width: 200px"
                            v-model:value="state.searchWeek"
                            picker="week"
                            :format="weekFormat"
                            @change="handleWeekChange"
                        />
                    </a-form-item>
                    <div>
                        <a-button type="primary" @click="exportToPDF">导出</a-button>
                    </div>
                </div>

                <a-tabs v-model:activeKey="state.activeKey" @change="tabChange">
                    <a-tab-pane key="1" tab="进展概况" />
                    <a-tab-pane key="2" tab="持续跟进事项" force-render />
                    <a-tab-pane key="3" tab="问题、风险及决策事项" />
                </a-tabs>
                <div class="default-table">
                    <a-table
                        v-if="state.activeKey === '1'"
                        bordered
                        :columns="state.columns"
                        :data-source="state.dataSource"
                        :scroll="{ y: 450 }"
                    >
                        <template #bodyCell="{ column, record, text }">
                            <template
                                v-if="column.dataIndex === 'progressGoals' || column.dataIndex === 'progressFinish'"
                            >
                                <div>
                                    <div class="align-left" v-for="(line, index) in text.split('\n')" :key="index">
                                        {{ line }}
                                    </div>
                                </div>
                            </template>
                        </template>
                    </a-table>
                    <a-table
                        v-if="state.activeKey === '2'"
                        bordered
                        :columns="state.columns1"
                        :data-source="state.dataSource1"
                        :scroll="{ y: 450 }"
                    >
                        <template #bodyCell="{ column, record, text }">
                            <template
                                v-if="
                                    column.dataIndex === 'remark' ||
                                    column.dataIndex === 'actionName' ||
                                    column.dataIndex === 'actionSuggest'
                                "
                            >
                                <div>
                                    <div class="align-left" v-for="(line, index) in text.split('\n')" :key="index">
                                        {{ line }}
                                    </div>
                                </div>
                            </template>
                        </template>
                    </a-table>
                    <a-table
                        v-if="state.activeKey === '3'"
                        bordered
                        :columns="state.columns2"
                        :data-source="state.dataSource2"
                        :scroll="{ y: 450 }"
                    >
                        <template #bodyCell="{ column, record, text }">
                            <template
                                v-if="
                                    column.dataIndex === 'remark' ||
                                    column.dataIndex === 'actionName' ||
                                    column.dataIndex === 'actionSuggest'
                                "
                            >
                                <div>
                                    <div class="align-left" v-for="(line, index) in text.split('\n')" :key="index">
                                        {{ line }}
                                    </div>
                                </div>
                            </template>
                        </template>
                    </a-table>
                </div>
            </div>
            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    import isoWeek from 'dayjs/plugin/isoWeek'

    dayjs.extend(isoWeek)
    onMounted(async () => {
        // 获取当前日期
        const today = dayjs()
        // 计算本周的周一和周日
        const startOfWeek = today.startOf('week').add(1, 'day').format('YYYY-MM-DD') // 周一
        const endOfWeek = today.endOf('week').add(1, 'day').format('YYYY-MM-DD') // 周日
        // 输出结果
        const currentWeekRange = [startOfWeek, endOfWeek]
        const s = dayjs(today).startOf('week').format('M月D日')
        const e = dayjs(today).endOf('week').format('M月D日')
        const timeFrame = [`${s}-${e}`]
        state.searchWeek = dayjs(startOfWeek)
        state.timeFrameList = currentWeekRange
        state.columns.forEach(item => {
            if (item.title !== '公司') {
                item.title = '[' + timeFrame + ']' + '     ' + item.title
            }
        })
        await getRegionList()
        getProgress()
    })
    const state = reactive({
        tabList: [],
        activeKey: '1',
        radioValue: '',
        searchWeek: '',
        timeFrame: '',
        timeFrameList: [],
        columns: [
            {
                title: '公司',
                align: 'center',
                dataIndex: 'projectName'
            },
            {
                title: `主要完成工作`,
                align: 'center',
                dataIndex: 'progressFinish'
            },
            {
                title: '主要工作目标',
                align: 'center',
                dataIndex: 'progressGoals'
            }
        ],
        dataSource: [],
        dataSource1: [],
        dataSource2: [],
        columns1: [
            {
                title: `公司`,
                align: 'center',
                dataIndex: 'company'
            },
            {
                title: '持续跟进事项',
                align: 'center',
                width: 200,
                dataIndex: 'actionName'
            },
            {
                title: '行动建议',
                align: 'center',
                width: 200,
                dataIndex: 'actionSuggest'
            },
            {
                title: '提出日期',
                align: 'center',
                width: 150,
                dataIndex: 'actionHappenDate'
            },
            {
                title: '预计完成日期',
                width: 150,
                align: 'center',
                dataIndex: 'actionFinishDate'
            },
            {
                title: '是否完成',
                align: 'center',
                width: 100,
                dataIndex: 'isFinish'
            },
            {
                title: '备注',
                align: 'center',
                width: 400,
                dataIndex: 'remark'
            }
        ],
        columns2: [
            {
                title: `公司`,
                align: 'center',
                dataIndex: 'company'
            },
            {
                title: '责任人',
                align: 'center',
                width: 100,
                dataIndex: 'responsibleName'
            },
            {
                title: '问题/风险/决策类型',
                align: 'center',
                width: 200,
                dataIndex: 'category'
            },
            {
                title: '问题/风险/决策事项描述',
                align: 'center',
                width: 200,
                dataIndex: 'actionName'
            },
            {
                title: '问题/风险等级 (高/中/低)',
                align: 'center',
                width: 200,
                dataIndex: 'problemRisk'
            },
            {
                title: '行动建议',
                align: 'center',
                width: 200,
                dataIndex: 'actionSuggest'
            },
            {
                title: '提出日期',
                align: 'center',
                width: 150,
                dataIndex: 'actionHappenDate'
            },
            {
                title: '预计完成日期',
                align: 'center',
                width: 150,
                dataIndex: 'actionFinishDate'
            },
            {
                title: '备注',
                width: 300,
                align: 'center',
                dataIndex: 'remark'
            }
        ]
    })
    // 日期格式化
    const weekFormat = date => {
        const year = date.year()
        const month = date.month() + 1
        // 获取当月的第一天
        const firstDayOfMonth = dayjs(date).startOf('month')
        // 计算当前日期是本月的第几周
        const weekOfMonth = date.week() - firstDayOfMonth.week() + 1
        return `${year}年${month}月第${weekOfMonth}周`
    }

    // 筛选日期格式化
    const handleWeekChange = date => {
        state.columns = [
            {
                title: '公司',
                align: 'center',
                dataIndex: 'projectName'
            },
            {
                title: `主要完成工作`,
                align: 'center',
                dataIndex: 'progressFinish'
            },
            {
                title: '主要工作目标',
                align: 'center',
                dataIndex: 'progressGoals'
            }
        ]
        if (date) {
            const startOfWeek = dayjs(date).startOf('week').format('M月D日')
            const endOfWeek = dayjs(date).endOf('week').format('M月D日')
            const start = dayjs(date).startOf('isoWeek').format('YYYY-MM-DD')
            const end = dayjs(date).endOf('isoWeek').format('YYYY-MM-DD')
            state.timeFrameList = [start, end]
            state.timeFrame = [`${startOfWeek}-${endOfWeek}`]

            state.columns.forEach(item => {
                if (item.title !== '公司') {
                    item.title = '[' + state.timeFrame + ']' + '     ' + item.title
                }
            })
        } else {
            state.timeFrame = []
            state.timeFrameList = []
            state.columns = [
                {
                    title: '公司',
                    align: 'center',
                    dataIndex: 'projectName'
                },
                {
                    title: `主要完成工作`,
                    align: 'center',
                    dataIndex: 'progressFinish'
                },
                {
                    title: '主要工作目标',
                    align: 'center',
                    dataIndex: 'progressGoals'
                }
            ]
        }
        tabChange(state.activeKey)
    }
    // 进展
    function getProgress() {
        post('/solution-ppm/api/v2/built-in-system-ppm/cooperation/kanban/progress', {
            regionId: state.radioValue,
            timeFrameList: state.timeFrameList
        }).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.dataSource = data.data
        })
    }
    // 事项
    function getAction() {
        post('/solution-ppm/api/v2/built-in-system-ppm/cooperation/kanban/action', {
            regionId: state.radioValue,
            timeFrameList: state.timeFrameList
        }).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.dataSource1 = data.data
        })
    }
    // 问题
    function getQuestion() {
        post('/solution-ppm/api/v2/built-in-system-ppm/cooperation/kanban/problem_risk_decision', {
            regionId: state.radioValue,
            timeFrameList: state.timeFrameList
        }).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.dataSource2 = data.data
        })
    }
    // 区域
    async function getRegionList() {
        try {
            const data = await get('/solution-ppm/api/v2/built-in-system-ppm/cooperation/config_region/display')
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.tabList = data.data
            state.radioValue = data.data[0]?.id
        } catch (error) {
            message.error('Failed to fetch region list')
        }
    }
    //     切换区域
    function radioChange() {
        getProgress()
        getAction()
        getQuestion()
    }
    function tabChange(activeKey) {
        if (activeKey === '1') {
            getProgress()
        } else if (activeKey === '2') {
            getAction()
        } else if (activeKey === '3') {
            getQuestion()
        }
    }
    // TODO:导出方法
    function downloadPdf(response, name) {
        const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
        })
        const downloadElement = document.createElement('a')
        const href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = name // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href)
        return href
    }

    function exportToPDF() {
        post(
            `/solution-ppm/api/v2/built-in-system-ppm/cooperation/kanban/progress_export`,
            {
                regionId: state.radioValue,
                timeFrameList: state.timeFrameList
            },
            {
                responseType: 'arraybuffer'
            }
        ).then(res => {
            let name = state.tabList.find(item => item.id == state.radioValue).regionName
            if (name) {
                downloadPdf(res, `${name}.pdf`)
            } else {
                downloadPdf(res, '项目总结.pdf')
            }
        })
    }
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    /*样式*/
    .top-tab {
        background: #ffffff;
        border-radius: 2px;
        height: 64px;
        padding: 16px 24px;
        margin-bottom: 18px;
    }
    .content {
        background: #ffffff;
        border-radius: 2px;
        padding: 24px;
        height: calc(100% - 120px);
    }
    .default-table:deep(.@{ant-prefix}-table-thead) > tr > th {
        background-color: #3875ff;
        color: #fff;
        font-weight: 600;
        padding: 8px 16px;
        border-right: 1px solid #d9d9d9;
    }
    .opration {
        display: flex;
        justify-content: space-between;
    }
    .align-left {
        text-align: left;
    }
</style>
